package cn.xuqiudong.demo.dubbo.common.tools;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 描述:
 * @author Vic.xu
 * @since 2022-01-24 10:13
 */
public class DubboTools {

    public static final String TRACE_ID = "dubbo-trance-id";

    /**
     * 保存在当前线程中的tranceId
     */
    public static final ThreadLocal<String> DUBBO_TRANCE_LOCAL = new ThreadLocal<>();
    /**
     * 保存在当前线程中的userInfo
     */
    //public static final ThreadLocal<SessionInfo> DUBBO_USER_LOCAL = new ThreadLocal<>();

    /**
     * 把trance id 存入当前线程
     * @param tranceId
     */
    public static void setLocalTranceId(String tranceId){
        DUBBO_TRANCE_LOCAL.set(tranceId);
    }

    public static void removeLocalTranceId(){
        DUBBO_TRANCE_LOCAL.remove();
    }

    /**
     * 获取当前线程中的trance id
     * @return trance id
     */
    public static String getLocalTranceId(){
        return DUBBO_TRANCE_LOCAL.get();
    }

    /**
     * 获取当前线程中的SessionInfo
     * @return SessionInfo
     */
    //public static SessionInfo getLocalSessionInfo(){
    //    return DUBBO_USER_LOCAL.get();
    //}

    //public static void setLocalSessionInfo(SessionInfo sessionInfo){
    //    DUBBO_USER_LOCAL.set(sessionInfo);
    //}

    //public static void removeLocalSessionInfo(){
    //    DUBBO_USER_LOCAL.remove();
    //}


    /**
     * 生成 tranceId =    uuid:sessionId
     * @return  tranceId
     */
    public static String generateTranceId(){
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyMMdd-HHmmss.SSS"));
        String pref = now + "-"  + uuid.substring(0, 4);
        //获取sessionId
        String sessionId = currentsessionId();
        if (sessionId == null) {
            sessionId = "-1";
        }
        return pref + ":" + sessionId;
    }

    public static String currentsessionId(){
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attr == null) {
            return null;
        }
        HttpSession session = attr.getRequest().getSession(false);
        if (session == null) {
            return null;
        }
        return session.getId();
    }

    public static void main(String[] args) {
        String s = generateTranceId();
        System.out.println(s);
    }
}
